package com.innovation.chengzhangriji.ui;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.innovation.chengzhangriji.Baby;
import com.innovation.chengzhangriji.BabyAndParent;
import com.innovation.chengzhangriji.Config;
import com.innovation.chengzhangriji.Parent;
import com.innovation.chengzhangriji.R;
import com.innovation.chengzhangriji.TimelinePhotoUrl;
import com.innovation.chengzhangriji.database.DatabaseManager;
import com.innovation.chengzhangriji.http.Auth;
import com.innovation.chengzhangriji.http.BabyAllResponse;
import com.innovation.chengzhangriji.http.Client;
import com.innovation.chengzhangriji.http.DataResponse;
import com.innovation.chengzhangriji.http.ResponseHandler;
import com.innovation.chengzhangriji.http.Token;
import com.innovation.chengzhangriji.http.TypeDataResponse;
import com.innovation.chengzhangriji.preferences.LoginInfo;
import com.innovation.chengzhangriji.ui.agent.HomeActivityAgent;
import com.innovation.chengzhangriji.ui.widget.CuteBabyAvatarView;
import com.innovation.chengzhangriji.ui.widget.CuteButton;
import com.innovation.chengzhangriji.ui.widget.CuteTextView;
import com.innovation.chengzhangriji.ui.widget.CuteToolbar;
import com.innovation.chengzhangriji.util.BabyUtil;
import com.makeramen.roundedimageview.RoundedImageView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.joda.time.DateTime;
import org.joda.time.Period;
import org.joda.time.PeriodType;
import org.json.JSONObject;

import java.util.ArrayList;

public class BabyDiaryActivity extends BaseActivity implements CuteToolbar.OnClickCuteToolbarListener {
    private RelativeLayout relativeLayout_guanzhuren, relativeLayout_zhaopian, relativeLayout_babydetail;
    private LoginInfo mLoginInfo;
    private BabyAllResponse[] info;
    private int length, count_photo = 0;
    private String name, ttime, logopath, mDay;
    private DisplayImageOptions options;
    private boolean isAdmin;
    private CuteBabyAvatarView imageView_head;
    private TextView tv_count_guanzhuren, tv_count_photo, tv_video_count, tv_name, tv_time;
    private Baby babys;
    private CuteToolbar toolbar;
    private CuteButton button_cancel;
    private ImageView iv_sex;
    private LinearLayout linearLayout;
    private CuteTextView tv_forcancle;
    private Parent[] parents;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                tv_count_photo.setText("" + count_photo);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_baby_diary);
        toolbar = (CuteToolbar) findViewById(R.id.baby_diary_toolbar);
        toolbar.setOnClickCuteToolbarListener(this);
        requestBabyAll();
        registerBoradcastReceiver();
        init();
    }

    // 查询日记照片或视频数量
    private void queryDiaryCount() {
        // 查询本地数据库的日记数量
        tv_video_count.setText(Config.getDiaryCount(this, Config.VIDEO_COUNT) + "");
        tv_count_photo.setText(Config.getDiaryCount(this, Config.PHOTO_COUNT) + "");
        Client.requestCountGet(this, mLoginInfo.getPhone(), mLoginInfo.getToken().getAccessToken(), mLoginInfo.getBabyID(),
                new ResponseHandler() {
                    @Override
                    public void onInnovationSuccess(JsonElement value) {
                        super.onInnovationSuccess(value);
                        JsonObject jsonObject = value.getAsJsonObject();
                        tv_count_photo.setText(jsonObject.get("Photo").getAsInt() + "");
                        tv_video_count.setText(jsonObject.get("Vedio").getAsInt() + "");
                        // 保存到本地
                        Config.setDiaryCount(BabyDiaryActivity.this,
                                jsonObject.get("Diary").getAsInt(),
                                jsonObject.get("Text").getAsInt(),
                                jsonObject.get("Photo").getAsInt(),
                                jsonObject.get("Audio").getAsInt(),
                                jsonObject.get("Vedio").getAsInt());
                    }
                }, new Client.NetworkUnavailableListener() {
                    @Override
                    public void networkUnavailable() {
                        tipShow(getString(R.string.tip_network_unavailable));
                    }
                }
        );
    }

    @Override
    protected void onResume() {
        super.onResume();

        count_photo = 0;
        mLoginInfo = Config.getLoginInfo(BabyDiaryActivity.this);
        String userId = mLoginInfo.getUserID();
        int babyId = mLoginInfo.getBabyID();
        parents = DatabaseManager.getInstance(BabyDiaryActivity.this).queryParent(babyId);
        babys = DatabaseManager.getInstance(BabyDiaryActivity.this).queryBaby(userId, babyId);
        if (babys == null) {
            tipShow("您已被取消对该宝宝的关注!");
            finish();
            return;
        }
        mDay = BabyUtil.getBabyDay(babys, System.currentTimeMillis());
        tv_time.setText(mDay);
        name = babys.getName();
        logopath = babys.getImageUrl();
        if (parents != null) {
            length = parents.length;
        }

        BabyAndParent babyAndParent = DatabaseManager.getInstance(BabyDiaryActivity.this).queryBabyAndParent(userId, babyId);
        isAdmin = babyAndParent.getRole() == 2;
        if (isAdmin) {
            if (parents == null || parents.length == 0) {
                return;
            } else if (parents.length == 1) {
                button_cancel.setText("删除日记本");
                button_cancel.setClickable(true);
                button_cancel.setBackgroundResource(R.drawable.btn_admin_cancel);
                linearLayout.setVisibility(View.GONE);
            } else {
                button_cancel.setText("删除日记本");
                button_cancel.setClickable(false);
                button_cancel.setBackgroundResource(R.drawable.btn_disable);
                linearLayout.setVisibility(View.VISIBLE);
            }
        } else {

        }
        setOptions();
        imageView_head.setAvatar(logopath);
        imageView_head.setSex(babys.getGender());
        tv_count_guanzhuren.setText("" + length);

        toolbar.setCuteTitle(name + "的成长日记");
        tv_name.setText(name);
        // 查询图片日记和照片数量
        queryDiaryCount();
    }

    private void init() {
        mLoginInfo = Config.getLoginInfo(BabyDiaryActivity.this);
        if (mLoginInfo == null) {
            return;
        }
        final int babyId = mLoginInfo.getBabyID();

        // 查询关注人
        button_cancel = (CuteButton) findViewById(R.id.baby_diary_notice_btn_cancel);
        button_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isAdmin) {
                    if (parents == null || parents.length == 0) {
                        return;
                    } else if (parents.length == 1) {
                        Intent intent = new Intent(BabyDiaryActivity.this, DeleteDialogActivity.class);
                        startActivityForResult(intent, 1002);
                    } else {
//                        Intent intent = new Intent(BabyDiaryActivity.this, CancleNoticeDialogActivity.class);
//                        intent.putExtra("name",name);
//                        startActivity(intent);
                    }
                } else {
                    onLongClickNote();
                }
            }
        });
        linearLayout = (LinearLayout) findViewById(R.id.linearlayout_role2);
        tv_forcancle = (CuteTextView) findViewById(R.id.tv_clickforcancle);
        // 设置中文字体加粗
        TextPaint tp = tv_forcancle.getPaint();
        tp.setFakeBoldText(true);
        tv_forcancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(BabyDiaryActivity.this, CancleNoticeDialogActivity.class);
                Gson gson2 = new Gson();
                String sInfo = gson2.toJson(info);
                intent.putExtra("info", sInfo);
                intent.putExtra("name", name);
                startActivity(intent);
            }
        });
        tv_name = (TextView) findViewById(R.id.baby_name);

        tv_time = (TextView) findViewById(R.id.baby_time_show);
        tv_time.setText(mDay);
        relativeLayout_babydetail = (RelativeLayout) findViewById(R.id.relativeLayout_babydetail);
        relativeLayout_babydetail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(BabyDiaryActivity.this, BabyDetailActivity.class);
                // intent.putExtra("babyId", getIntent().getIntExtra("babyId", 0));
                startActivity(intent);
            }
        });
        tv_count_guanzhuren = (TextView) findViewById(R.id.count_guanzhuren);
        tv_count_photo = (TextView) findViewById(R.id.count_zhaopian);
        tv_count_photo.setText("" + 0);
        tv_video_count = (TextView) findViewById(R.id.count_video);
        tv_video_count.setText("" + 0);
        imageView_head = (CuteBabyAvatarView) findViewById(R.id.baby_photo);
        relativeLayout_guanzhuren = (RelativeLayout) findViewById(R.id.relativeLayout_guanzhuren);
        relativeLayout_guanzhuren.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(BabyDiaryActivity.this, BabynoticeActivity.class);
                startActivityForResult(intent, 1000);
            }
        });
        relativeLayout_zhaopian = (RelativeLayout) findViewById(R.id.relativeLayout_zhaopian);
        relativeLayout_zhaopian.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(BabyDiaryActivity.this, HistoryPhotoActivity.class);
                startActivity(intent);
            }
        });
    }

    private void setOptions() {
        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.mipmap.gray_head)    //在ImageView加载过程中显示图片
                .showImageForEmptyUri(R.mipmap.gray_head)  //image连接地址为空时
                .showImageOnFail(R.mipmap.gray_head)  //image加载失败
                .cacheOnDisk(true)   //加载图片时会在磁盘中加载缓存
                .build();
    }

    @Override
    public void onClickLeft() {
        onBackPressed();
    }

    @Override
    public void onClickRight() {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == 1000) {
                if (data != null && data.getBooleanExtra(Config.EXTRA_CAN_BACK, true)) {
                    setResult(RESULT_OK, data);
                    finish();
                }
//            }else  if (requestCode == 1001 && resultCode == RESULT_OK) {
//                    updateDb();
            } else if (requestCode == 1002 && resultCode == RESULT_OK) {
                delete();
            }
        }
    }

    // 启动历史视频页面
    public void startHistoryVideoActivity(View v) {
        Intent intent = new Intent(this, HistoryVideoActivity.class);
        startActivity(intent);
    }

    public void onLongClickNote() {

        // 网络请求删除
        final LoginInfo loginInfo = Config.getLoginInfo(BabyDiaryActivity.this);
        if (loginInfo == null) {
            return;
        }
        final String phone = loginInfo.getPhone();
        final String token = loginInfo.getToken().getAccessToken();
        final String userID = loginInfo.getUserID();
        final int babyID = babys.getBabyID();
        // 判断权限
        BabyAndParent babyAndParent = DatabaseManager.getInstance(BabyDiaryActivity.this).queryBabyAndParent(userID, babyID);
        if (babyAndParent.getRole() == 2) {
            Intent intent = new Intent(BabyDiaryActivity.this, TipDeleteDialogActivity.class);
            startActivity(intent);
            return;
        }

        new AlertDialog.Builder(this).setTitle("取消对日记本的关注")
                .setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Client.requestRemoveNote(BabyDiaryActivity.this, phone, token, babyID, new ResponseHandler() {

                            @Override
                            public void onInnovationStart() {
                                showProgressDialog(null, null);
                            }

                            @Override
                            public void onInnovationSuccess(JsonElement value) {
                                // 移除本地宝宝
                                DatabaseManager.getInstance(BabyDiaryActivity.this).deleteBaby(babyID);
                                // 发送删除通知
                                // sendBroadcast(new Intent("delete"));

                                dismissProgressDialog();
                                Intent intent = new Intent();
                                intent.putExtra(Config.EXTRA_CAN_BACK, true);
                                setResult(RESULT_OK, intent);
                                finish();
                            }

                            @Override
                            public void onChZhRJFailure(String value) {
                                dismissProgressDialog();
                                tipShow(value);
                            }

                            @Override
                            public void onChZhRJTokenFailure(String value) {
                                dismissProgressDialog();
                                tipShow(value);
                            }

                        }, networkUnavailableSampleImpl());
                    }
                })
                .setNegativeButton("否", null)
                .show();
    }

    private void requestBabyAll() {
        LoginInfo loginInfo = Config.getLoginInfo(BabyDiaryActivity.this);
        if (loginInfo == null) {
            return;
        }
        String phone = loginInfo.getPhone();
        String token = loginInfo.getToken().getAccessToken();
        final String userId = loginInfo.getUserID();
        final int babyId = loginInfo.getBabyID();
//        BabyAndParent babyAndParent = DatabaseManager.getInstance(BabyDiaryActivity.this).queryBabyAndParent(userId, babyId);
//        isAdmin = babyAndParent.getRole() == 2;

        // 判断网络
        if (!isNetworkConnect(BabyDiaryActivity.this)) {
            parents = DatabaseManager.getInstance(BabyDiaryActivity.this).queryParent(babyId);
            if (parents == null || parents.length == 0) {
                return;
            }
            BabyAllResponse[] responses = new BabyAllResponse[parents.length];
            length = responses.length;
            info = responses;

            return;
        }
        Client.requestBabyAll(BabyDiaryActivity.this, phone, token, babyId, new ResponseHandler() {

            @Override
            public void onInnovationSuccess(JsonElement value) {
                super.onInnovationSuccess(value);
                JsonObject object = value.getAsJsonObject();
                JsonArray jsonArray = object.getAsJsonArray("Messages");
                BabyAllResponse[] responses = get(jsonArray.toString(), BabyAllResponse[].class);
                if (responses == null) {
                    return;
                }
                length = responses.length;
                info = responses;
                parents = new Parent[responses.length];
                for (int i = 0; i < responses.length; i++) {
                    parents[i] = new Parent();
                    parents[i].setBabyId(babyId);
                    parents[i].setType(responses[i].getType());
                    parents[i].setParentId(responses[i].getUserId());
                    parents[i].setUser(responses[i].getUser());
                    parents[i].setName(responses[i].getName());
                    parents[i].setPhone(responses[i].getPhone());
                    parents[i].setServerTS(responses[i].getServerTS());
                    parents[i].setMessage(responses[i].getMessage());
                    parents[i].setPath(responses[i].getPath());
                    parents[i].setNickName(responses[i].getNickName());
                    parents[i].setRole(responses[i].getAuth().getRole());
                    parents[i].setPermission(responses[i].getAuth().getPermission());
                    parents[i].setRange(responses[i].getAuth().getRange());
                }
                DatabaseManager.getInstance(BabyDiaryActivity.this).deleteAllParents(babyId);
                DatabaseManager.getInstance(BabyDiaryActivity.this).insertOrReplaceInTxParent(parents);

            }

        }, new Client.NetworkUnavailableListener() {
            @Override
            public void networkUnavailable() {

            }
        });
    }

    private static boolean isNetworkConnect(Context context) {
        ConnectivityManager conMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (conMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED
                || conMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED
                || conMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTING
                || conMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTING) {
            return true;
        } else if (conMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.DISCONNECTED
                || conMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.DISCONNECTED) {
            return false;
        }
        return false;
    }

    private void updateDb() {
        final LoginInfo loginInfo = Config.getLoginInfo(this);
        final String userId = loginInfo.getUserID();
        final String phone = loginInfo.getPhone();
        final String token = loginInfo.getToken().getAccessToken();
        final int babyId = loginInfo.getBabyID();
        Client.requestBabyAll(BabyDiaryActivity.this, phone, token, babyId, new ResponseHandler() {

            @Override
            public void onInnovationSuccess(JsonElement value) {
                super.onInnovationSuccess(value);
                JsonObject object = value.getAsJsonObject();
                JsonArray jsonArray = object.getAsJsonArray("Messages");
                BabyAllResponse[] responses = get(jsonArray.toString(), BabyAllResponse[].class);
                if (responses == null) {
                    return;
                }
                Parent[] parents = new Parent[responses.length];
                for (int i = 0; i < responses.length; i++) {
                    parents[i] = new Parent();
                    parents[i].setBabyId(babyId);
                    parents[i].setType(responses[i].getType());
                    parents[i].setParentId(responses[i].getUserId());
                    parents[i].setUser(responses[i].getUser());
                    parents[i].setName(responses[i].getName());
                    parents[i].setPhone(responses[i].getPhone());
                    parents[i].setServerTS(responses[i].getServerTS());
                    parents[i].setMessage(responses[i].getMessage());
                    parents[i].setPath(responses[i].getPath());
                    parents[i].setNickName(responses[i].getNickName());
                    parents[i].setRole(responses[i].getAuth().getRole());
                    parents[i].setPermission(responses[i].getAuth().getPermission());
                    parents[i].setRange(responses[i].getAuth().getRange());
                }
                DatabaseManager.getInstance(BabyDiaryActivity.this).deleteAllParents(babyId);
                DatabaseManager.getInstance(BabyDiaryActivity.this).insertOrReplaceInTxParent(parents);
                finish();
            }

        }, networkUnavailableSampleImpl());
    }

    private void delete() {
        // 网络请求删除
        final LoginInfo loginInfo = Config.getLoginInfo(this);
        if (loginInfo == null) {
            return;
        }
        String phone = loginInfo.getPhone();
        String token = loginInfo.getToken().getAccessToken();
        final int babyID = loginInfo.getBabyID();
        Client.requestRemoveNote(this, phone, token, babyID, new ResponseHandler() {

            @Override
            public void onInnovationStart() {
                showProgressDialog(null, null);
            }

            @Override
            public void onInnovationSuccess(JsonElement value) {
//                dismissProgressDialog();
//                sendDeleteBroadcast();
//                setResult(-1000);
//                finish();
                dismissProgressDialog();
                // 删除宝宝信息
                DatabaseManager.getInstance(BabyDiaryActivity.this).deleteBaby(babyID);
                Intent intent = new Intent();
                intent.putExtra(Config.EXTRA_CAN_BACK, true);
                setResult(RESULT_OK, intent);
                finish();
//                updateDb();
            }

            @Override
            public void onChZhRJFailure(String value) {
                dismissProgressDialog();
                tipShow(value);
            }

            @Override
            public void onChZhRJTokenFailure(String value) {
                dismissProgressDialog();
                tipShow(value);
            }

        }, networkUnavailableSampleImpl());
    }

    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals("" + 100)) {
                finish();
            }
        }
    };

    public void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction("" + 100);
        //注册广播
        registerReceiver(mBroadcastReceiver, myIntentFilter);
    }
}
